/**
 * 
 */
package com.brainstrongtech.bfs.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.brainstrongtech.bfs.domian.User;
import com.brainstrongtech.bfs.domian.UserConfigParam;
import com.brainstrongtech.bfs.service.SecurityService;
import com.brainstrongtech.bfs.service.UserService;
import com.brainstrongtech.bfs.util.Message;

/**
 * 
 * @Description:
 * @author: tianhua.xie
 * @Date: 2017年4月4日 下午3:41:06
 * 
 */
@Controller
@RequestMapping("/securityController")
public class SecurityController extends BaseController {

	@Autowired
	private SecurityService securityService;
	@Autowired
	private UserService userService;

	@RequestMapping("/toLogin")
	public String toLogin(ModelMap modelMap) throws Exception {
		User user = new User();
		user.setUserAccount("Xth8013");
		user.setUserPwd("xiami");
		modelMap.put("user", user);
		return "login";
	}

	@RequestMapping("/checkUser")
	@ResponseBody
	public Message checkUserByAccount(@RequestParam String account) throws Exception {
		Message message = null;
		try {

			Boolean isExisted = securityService.isExistUser(account);
			message = coverMessage("200", "查询成功", isExisted);

		} catch (Throwable e) {
			e.printStackTrace();
			message = coverMessage("500", e.getMessage());
		}

		return message;
	}

	@RequestMapping("/login")
	public String login(HttpServletRequest request, ModelMap modelMap, User user) throws Exception {

		try {
			user = securityService.login(user.getUserAccount(), user.getUserPwd());
			request.getSession().setAttribute("loginedUser", user);
			UserConfigParam param = userService.loadUserConfigParamById(user.getUserId());
			request.getSession().setAttribute("configParam", param);
		} catch (Exception e) {
			e.printStackTrace();
			modelMap.put("loginMsg", e.getMessage());
			return "login";
		}

		return "redirect:/mainController/toMainMenu";
	}

	@RequestMapping("/logout")
	public String logout(HttpServletRequest request) throws Exception {
		request.getSession().removeAttribute("loginedUser");
		request.getSession().removeAttribute("configParam");
		request.getSession().invalidate();
		return "redirect:/securityController/toLogin";
	}
}
